package com.zj.zhao.reflection;

import com.zj.zhao.reflection.annotation.MyAutowired;
import com.zj.zhao.reflection.bean.UserController;
import com.zj.zhao.reflection.bean.UserService;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.stream.Stream;

public class ReflectionLambdoDemo {

    public static void main(String[] args) {
        UserController userController = new UserController();
//        UserService userService = new UserService();

        // 获取 class 对象
        Class<? extends UserController> clazz = userController.getClass();
        Stream.of(clazz.getDeclaredFields()).forEach(field -> {
            // 获取属性是否有注解 MyAutowired
            MyAutowired annotation = field.getAnnotation(MyAutowired.class);
            if (Objects.nonNull(annotation)) {
                field.setAccessible(true);
                // 获取当前属性的类型，有了类型之后可以创建具体的对象
                Class<?> type = field.getType();
                // 通过类型来创建对象，并完成注入
                try {
                    Object value = type.newInstance();
                    field.set(userController, value);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

        System.out.println(userController);
    }
}
